package org.goldenport.g3.servlet

import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConverters._
import javax.servlet._
import javax.servlet.http._
import org.goldenport.g3._
import org.goldenport.g3.messages.{Record, Html}
import org.goldenport.g3.messages.http._
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import org.apache.commons.fileupload.servlet.ServletFileUpload
import org.apache.commons.fileupload.FileItem

/*
 * @since   Sep. 24, 2010
 * @version Sep. 24, 2010
 * @version Nov. 13, 2011
 * @author  ASAMI, Tomoharu
 */
object ServletUtil {
  lazy val servletFileUpload: ServletFileUpload = {
    val factory = new DiskFileItemFactory()
    new ServletFileUpload(factory)
  }

  def fileItems(req: HttpServletRequest): List[FileItem] = {
    servletFileUpload.parseRequest(req).asScala.toList collect {
      case item: FileItem if !item.isFormField() => item
    }
  }

  def formItems(req: HttpServletRequest): List[FileItem] = {
    servletFileUpload.parseRequest(req).asScala.toList collect {
      case item: FileItem if item.isFormField() => item
    }
  }

  def makeRecord(req: HttpServletRequest): Option[Record] = {
    val names = req.getParameterNames().asScala
    val rs = new Record
    for (name <- names) {
      rs.put(Symbol(name.toString), req.getParameter(name.toString))
    }
    if (rs.isEmpty) None
    else Some(rs)
  }
}
